/**
 * @Description: 自定义图层
 * @Author: 程前
 * @Date: 2024-05-31 14:16:47
 * @LastEditors: 程前
 * @LastEditTime: 2025-02-18 16:29:34
 */
import {
  UrlTemplateImageryProvider,
  WebMapServiceImageryProvider,
  WebMapTileServiceImageryProvider,
} from "cesium";
import { replacePlaceholders } from "@/utils";


const loadXyz = (options: UrlTemplateImageryProvider.ConstructorOptions) => {
  const url: string = replacePlaceholders(options.url, options);
  const LayerOption: UrlTemplateImageryProvider.ConstructorOptions = {
    ...options,
    url: url,
    subdomains: options.subdomains || [],
    maximumLevel: options.maximumLevel || undefined,
    minimumLevel: options.minimumLevel || undefined,
  };
  return new UrlTemplateImageryProvider(LayerOption);
};

const loadWms = (options: WebMapServiceImageryProvider.ConstructorOptions) => {
  const url: string = replacePlaceholders(options.url, options);
  const LayerOption: WebMapServiceImageryProvider.ConstructorOptions = {
    ...options,
    url: url,
    layers: options.layers || "",
    subdomains: options.subdomains || [],
    maximumLevel: options.maximumLevel || undefined,
    minimumLevel: options.minimumLevel || undefined,
  };
  return new WebMapServiceImageryProvider(LayerOption);
};

const loadWmts = (
  options: WebMapTileServiceImageryProvider.ConstructorOptions
) => {
  const url: string = replacePlaceholders(options.url, options);
  const LayerOption: WebMapTileServiceImageryProvider.ConstructorOptions = {
    ...options,
    url: url,
    layer: options.layer || "",
    style: options.style || "",
    tileMatrixSetID: options.tileMatrixSetID || "",
    subdomains: options.subdomains || [],
    maximumLevel: options.maximumLevel || undefined,
    minimumLevel: options.minimumLevel || undefined,
  };
  return new WebMapTileServiceImageryProvider(LayerOption);
};

export const createCustomImageryProvider = (opts: any) => {
  if (!opts.url) {
    throw new Error("url 必须为正确的影像、电子、矢量等地图的地址！");
  }
  const type = opts?.type ? opts.type.toUpperCase() : "XYZ";
  if (type === "WMS") {
    return loadWms(opts);
  } else if (type === "WMTS") {
    return loadWmts(opts);
  } else {
    return loadXyz(opts);
  }
};
